<template>
  <el-tabs tab-position="left">
    <el-tab-pane label="Query">
      <div class="searchSQL">
        <div class="flex-right">
          <el-select
            size="mini"
            placeholder="选择SQL"
            @change="selectSQLHandle"
            v-model="defalutSQLIndex"
          >
            <el-option
              v-for="item in sqlDataSelect"
              :key="item.SQL"
              :label="item.label"
              :value="item.key"
            >
              {{ item.label }}
            </el-option>
          </el-select>

          <el-select
            size="mini"
            v-model="selectDataSourceId"
            placeholder="选择数据源"
          >
            <el-option
              v-for="item in dataSources"
              :key="item.dataSourceId"
              :label="item.dataSourceType"
              :value="item.dataSourceId"
            >
              {{ item.dataSourceType + " - " + item.databaseName }}
            </el-option>
          </el-select>
          <el-button-group>
            <el-button
              @click="getSQLData"
              size="mini"
              type="primary"
              icon="el-icon-search"
            ></el-button>
            <el-button
              @click="clearSQL"
              size="mini"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
          </el-button-group>
        </div>
        <codemirror
          ref="myCm"
          :value="sqlStr"
          :options="cmOptions"
          @input="onSQLChange"
        >
        </codemirror>
      </div>
    </el-tab-pane>
    <el-tab-pane label="查询结果">
      <json-view
        :data="sqlData"
        theme="one-dark"
        style="height: 35vh; overflow: auto"
      />
    </el-tab-pane>
    <el-tab-pane label="处理数据">
      <div class="flex-right">
        <el-button type="primary" size="mini" @click="changeSQLData"
          >转换</el-button
        >
      </div>
      <codemirror
        ref="myCmJs"
        :value="dataHandleFunStr"
        :options="jsOptions"
        @input="onJsChange"
      />
    </el-tab-pane>
    <el-tab-pane label="渲染数据">
      <json-view
        :data="dataHandleRes"
        theme="one-dark"
        style="height: 35vh; overflow: auto"
      />
    </el-tab-pane>
    <!-- 参数弹窗 -->
    <el-dialog title="请输入默认参数" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item
          label="数据展示条数"
          v-if="form.top != undefined"
          :label-width="formLabelWidth"
         
        >
          <el-input v-model="form.top" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="关区"
          v-if="form.customs != undefined"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.customs" placeholder="请选择">
            <el-option
              v-for="item in customs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSQL">确 定</el-button>
      </div>
    </el-dialog>
  </el-tabs>
</template>
<script>
import { codemirror } from "vue-codemirror";
import { request } from "../../utils";
import { SQLArray, SelectCustoms } from "./js/SQLData";
import jsonView from "vue-json-views";
// require styles
import "codemirror/mode/sql/sql";
import "codemirror/mode/javascript/javascript";
import "codemirror/theme/base16-dark.css";
import "codemirror/theme/material-darker.css";
import "codemirror/lib/codemirror.css";
export default {
  props: {},
  components: {
    codemirror,
    jsonView,
  },

  data() {
    return {
      defalutSQLIndex: undefined,
      sqlDataSelect: SQLArray.map((s, i) => ({
        ...s,
        key: i,
        label: s.SHOW_NAME,
      })),
      // SQL 项目
      SQLParam: '',
      cmOptions: {
        mode: "text/x-sql",
        theme: "base16-dark",
        // readOnly: true,
      },
      dataSources: [],
      selectDataSourceId: null,
      sqlData: [],
      sqlStr: "",
      // 处理数据的方法和结果
      jsOptions: {
        mode: "javascript",
        theme: "material-darker",
      },
      dataHandleRes: [],
      dataHandleFunStr: `/**
* 处理 SQL 返回数据的脚本
* @param { Array<any> } data: SQL 语句返回的数据
* @return { Array<any> } 返回图表对应所需要的数据
*/
function handler(data){
  // 这里可修改数据展示
  return data
}`,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {},
      customs: SelectCustoms,
    };
  },
  created() {
    this.getDataSource();
  },
  watch: {
    "$store.state.sqlStr":function(val){
      this.sqlStr = val;
    },
    "$store.state.sqlParam":function(val){
      this.SQLParam = val;
    },
    "$store.state.sqlSource":function(val){
      this.selectDataSourceId = val.dataSourceId;
    },
    "$store.state.sqlData":function(val){
      this.sqlData = val;
    },
    "$store.state.sqlHandle":function(val){
      this.dataHandleFunStr = val;
    },
  },
  methods: {
    onSQLChange(value) {
      this.sqlStr = value;
    },
    clearSQL() {
      this.sqlStr = "";
    },
    onJsChange(value) {
      this.dataHandleFunStr = value;
    },
    selectSQLHandle(key) {
      const selectSQL = this.sqlDataSelect[key];
      const { DATA_SOURCE_ID, SQL, ORTHER_DATA } = selectSQL;
      if (ORTHER_DATA) {
        this.SQLParam = ORTHER_DATA;
      }
      this.sqlStr = SQL;
      this.selectDataSourceId = String(DATA_SOURCE_ID);
      this.defalutSQLIndex = key;
    },
    // 转化成功
    changeSQLData() {
      try {
        const funBody = this.dataHandleFunStr.split("handler(data)")[1].trim();
        if (!funBody) {
          this.$message({
            showClose: true,
            message: "请检查处理函数",
            type: "error",
          });
          return;
        }
        if (!this.sqlData.length) {
          this.$message({
            showClose: true,
            message: "SQL数据为空",
            type: "error",
          });
          return;
        }
        // const data = JSON.parse(JSON.stringify(this.sqlData));
        const fun = new Function("data", funBody);
        const dataRes = fun(this.sqlData);
        this.dataHandleRes = dataRes;
        this.$store.commit("setSQLHandleData", {
          sqlHandle: this.dataHandleFunStr,
          sqlHandleData: dataRes,
        });

        this.$message({
          showClose: true,
          message: "数据转换成功",
          type: "success",
        });
      } catch (error) {
        console.error(error);
        this.$message({
          showClose: true,
          message: "处理脚本有误，请检查",
          type: "error",
        });
      }
    },
    // 获取数据源
    getDataSource() {
      request({
        method: "GET",
        url: this.portInterface.getDataSources,
      }).then((res) => {
        this.dataSources = res.result;
      });
    },

    // 查询SQL数据
    getSQLData() {
      if (!this.selectDataSourceId) {
        this.$message({
          showClose: true,
          message: "请先选择数据源",
          type: "error",
        });
        return;
      }
      if (!this.sqlStr) {
        this.$message({
          showClose: true,
          message: "请先输入SQL",
          type: "error",
        });
        return;
      }
      // SQL this.sqlStr
      const paramsArr = this.sqlStr.match(/#{\w+,\w+=\w+}/g);
      if (paramsArr != null) {
        const filterArr = paramsArr.filter((item) => {
          return !item.startsWith("#{o");
        });
        const params = {};
        filterArr.map((item) => {
          const arr = item.match(/\w+/g);
          const key = arr[0];
          if (params[key] != undefined) {
            return;
          }
          if (key == "top") {
            params[key] = 10;
          } else if (key == "customs") {
            params[key] = "";
          }
        });
        this.form = params;
        this.dialogFormVisible = true;
      } else {
        this.getDataBySQL();
      }
    },
    confirmSQL() {
      this.form.top = Number(this.form.top);
      this.SQLParam = JSON.stringify(this.form);
      this.getDataBySQL();
    },
    getDataBySQL() {
      request({
        method: "POST",
        url: this.portInterface.getDataBySQL,
        data: {
          // chartId: 0,
          dataSourceId: this.selectDataSourceId,
          ortherData: this.SQLParam,
          sql: this.sqlStr,
        },
      }).then((res) => {
        if (res.result) {
          this.sqlData = res.result;
          const sqlSource = this.dataSources.find(
            (item) => item.dataSourceId === this.selectDataSourceId
          );
          this.$store.commit("setSQLData", {
            sqlData: res.result,
            sqlStr: this.sqlStr,
            sqlParam: this.SQLParam,
            sqlSource: sqlSource,
          });
        } else {
          this.$message({
            showClose: true,
            message: "查询数据为空，请检查 SQL 语句...",
            type: "warn",
          });
        }
        this.dialogFormVisible = false;
      });
    },
  },
};
</script>
<style scoped lang="less">
.el-tabs {
  background-color: #13227a;
}

.flex-right {
  display: flex;
  justify-content: flex-end;
  padding: 4px 12px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
}
/deep/.el-tabs__item {
  color: rgba(255, 255, 255, 0.3);
}
/deep/.el-tabs__item.is-active {
  color: #409eff;
}
.vue-codemirror {
  height: 88% !important;
  /deep/.CodeMirror {
    height: 100%;
  }
}
/deep/.el-tabs__content,
/deep/.el-tabs__content > div,
.searchSQL {
  height: 100%;
}
/deep/.el-tabs__content {
  overflow: auto;
}
/deep/.el-tabs__content::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}
@media screen and (max-width: 1280px) {
}
</style>
